package com.studentmanagement.ui;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.User;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.StudentService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class MyCoursePanel extends JPanel {
    private User currentUser;
    private CourseService courseService;
    private EnrollmentService enrollmentService;
    private StudentService studentService;
    
    private JTable courseTable;
    private DefaultTableModel tableModel;
    private JButton viewDetailButton;
    private JButton dropCourseButton;
    private JButton refreshButton;

    public MyCoursePanel(User user) {
        this.currentUser = user;
        this.courseService = new CourseService();
        this.enrollmentService = new EnrollmentService();
        this.studentService = new StudentService();
        
        initComponents();
        setupLayout();
        setupListeners();
        loadCourseData();
    }

    private void initComponents() {
        // 表格列名
        String[] columnNames = {"课程代码", "课程名称", "教师", "学分", "上课时间", "教室", "成绩", "状态"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        courseTable = new JTable(tableModel);
        courseTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        courseTable.getTableHeader().setReorderingAllowed(false);
        courseTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        courseTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        courseTable.setRowHeight(30);
        
        // 按钮初始化
        viewDetailButton = new JButton("查看详情");
        dropCourseButton = new JButton("退选课程");
        refreshButton = new JButton("刷新");
        
        // 设置按钮字体
        Font buttonFont = new Font("微软雅黑", Font.PLAIN, 14);
        viewDetailButton.setFont(buttonFont);
        dropCourseButton.setFont(buttonFont);
        refreshButton.setFont(buttonFont);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        JLabel titleLabel = new JLabel("我的课程");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titlePanel.add(titleLabel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(viewDetailButton);
        buttonPanel.add(dropCourseButton);
        buttonPanel.add(refreshButton);

        // 创建北部面板，包含标题和按钮
        JPanel northPanel = new JPanel(new BorderLayout());
        northPanel.add(titlePanel, BorderLayout.WEST);
        northPanel.add(buttonPanel, BorderLayout.EAST);

        // 添加组件到主面板
        add(northPanel, BorderLayout.NORTH);
        add(new JScrollPane(courseTable), BorderLayout.CENTER);
    }

    private void setupListeners() {
        viewDetailButton.addActionListener(e -> onViewDetail());
        dropCourseButton.addActionListener(e -> onDropCourse());
        refreshButton.addActionListener(e -> loadCourseData());
    }

    private void loadCourseData() {
        tableModel.setRowCount(0);
        List<Enrollment> enrollments = enrollmentService.getEnrollmentsByStudentId(
            studentService.getStudentByUserId(currentUser.getId()).getId()
        );
        
        for (Enrollment enrollment : enrollments) {
            Course course = courseService.getCourseById(enrollment.getCourseId());
            Object[] rowData = {
                course.getCourseCode(),
                course.getName(),
                course.getTeacherName() != null ? course.getTeacherName() : "未分配",
                course.getCredits(),
                course.getSchedule(),
                course.getClassroom(),
                enrollment.getGrade() != null ? enrollment.getGrade() : "暂无",
                formatStatus(enrollment.getStatus())
            };
            tableModel.addRow(rowData);
        }
    }

    private void onViewDetail() {
        int selectedRow = courseTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一门课程！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String courseCode = (String) tableModel.getValueAt(selectedRow, 0);
        Course course = courseService.getCourseByCourseCode(courseCode);
        
        if (course != null) {
            StringBuilder details = new StringBuilder();
            details.append("课程详情：\n\n");
            details.append("课程代码：").append(course.getCourseCode()).append("\n");
            details.append("课程名称：").append(course.getName()).append("\n");
            details.append("授课教师：").append(course.getTeacherName() != null ? course.getTeacherName() : "未分配").append("\n");
            details.append("开课院系：").append(course.getDepartment()).append("\n");
            details.append("学分：").append(course.getCredits()).append("\n");
            details.append("课程容量：").append(course.getCapacity()).append("\n");
            details.append("上课时间：").append(course.getSchedule()).append("\n");
            details.append("上课地点：").append(course.getClassroom()).append("\n");
            details.append("课程描述：").append(course.getDescription());

            JTextArea textArea = new JTextArea(details.toString());
            textArea.setEditable(false);
            textArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(400, 300));

            JOptionPane.showMessageDialog(this, scrollPane, "课程详情", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void onDropCourse() {
        int selectedRow = courseTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择一门课程！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String status = (String) tableModel.getValueAt(selectedRow, 7);
        if (!"已选".equals(status)) {
            JOptionPane.showMessageDialog(this, "只能退选\"已选\"状态的课程！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要退选该课程吗？\n退选后需要重新选课才能恢复。",
            "确认退选",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE);

        if (confirm == JOptionPane.YES_OPTION) {
            String courseCode = (String) tableModel.getValueAt(selectedRow, 0);
            Course course = courseService.getCourseByCourseCode(courseCode);
            boolean success = enrollmentService.dropCourse(
                studentService.getStudentByUserId(currentUser.getId()).getId(),
                course.getId()
            );

            if (success) {
                JOptionPane.showMessageDialog(this, "退选成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                loadCourseData(); // 刷新数据
            } else {
                JOptionPane.showMessageDialog(this, "退选失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private String formatStatus(String status) {
        if (status == null) return "未知";
        switch (status.toUpperCase()) {
            case "ACTIVE": return "已选";
            case "DROPPED": return "已退选";
            case "COMPLETED": return "已完成";
            default: return status;
        }
    }
} 